package com.example.demo.controller;

import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

public class FileUploadController {
    @PostMapping("/upload")
    public String up(String username, MultipartFile photo, HttpServletRequest request)throws IOException {
        System.out.println(username);
        System.out.println(photo.getOriginalFilename());//文件名称
        System.out.println(photo.getContentType());//文件类型
        System.out.println(System.getProperty("user.dir"));
        String path = request.getServletContext().getRealPath("/upload");//获取web服务器的运行目录
        System.out.println(path);
        saveFile(photo, path);
        return "Upload sucessed";
    }

    public void saveFile(MultipartFile photo, String path) throws IOException {
        File dir = new File(path);
        if(dir.exists()){
            dir.mkdirs();
        }
        File file = new File(path+photo.getOriginalFilename());
        photo.transferTo(file);
    }
}
